package cn.doitedu.hive.udf;

import org.apache.hadoop.hive.ql.exec.UDFArgumentException;
import org.apache.hadoop.hive.ql.metadata.HiveException;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDF;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.IntObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory;
import org.apache.hadoop.io.Text;

public class BitStr2Int extends GenericUDF {
    @Override
    public ObjectInspector initialize(ObjectInspector[] arguments) throws UDFArgumentException {
        return PrimitiveObjectInspectorFactory.javaIntObjectInspector;
    }

    @Override
    public Object evaluate(DeferredObject[] arguments) throws HiveException {
        Text bitText = (Text) arguments[0].get();
        String bit = bitText.toString();
        int s = 0;
        String[] chars = bit.split("");
        for(int i=bit.length()-1;i>-1;i--){
            s += Integer.parseInt(chars[i]) * (1 << (bit.length()-1)-i);
        }
        return s;
    }

    @Override
    public String getDisplayString(String[] children) {
        return null;
    }
}
